package window

// NewWindow 创建一个窗口，窗口大小为bucketSize * bucket
func NewWindow(bucket int) *Window {
	bli := make([]*Bucket, bucket)
	bli[bucket-1] = &Bucket{}
	for i := bucket - 2; i >= 0; i-- {
		bli[i] = &Bucket{
			Next: bli[i+1],
		}
	}
	bli[bucket-1].Next = bli[0]
	return &Window{
		bucket: bli,
		size:   bucket,
	}
}

// Window 窗口
type Window struct {
	bucket []*Bucket // 桶
	size   int       // 桶数量
}

// Append 向指定的桶追加一个数据
func (w *Window) Append(offset int, val float64) {
	w.bucket[offset%w.size].Append(val)
}

// Add 将指定桶中的数据加上指定值
func (w *Window) Add(offset int, val float64) {
	if w.bucket[offset%w.size].Count == 0 {
		w.bucket[offset%w.size].Append(val)
	} else {
		w.bucket[offset%w.size].Add(0, val)
	}
}

// ResetBuckets 重制从start开始count个桶
func (w *Window) ResetBuckets(start int, count int) {
	for i := 0; i < count; i++ {
		w.bucket[(start+i)%w.size].Reset()
	}
}

func (w *Window) Iterator(offset int, count int) Iterator {
	return Iterator{
		count:  count,
		bucket: w.bucket[offset%w.size],
	}
}
